package com.example.myproject.client;

import java.util.ArrayList;

import com.allen_sauer.gwt.dnd.client.drop.GridConstrainedDropController;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.ui.AbsolutePanel;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.Grid;
import com.google.gwt.user.client.ui.Image;
import com.google.gwt.user.client.ui.LayoutPanel;
import com.google.gwt.user.client.ui.ListBox;
import com.google.gwt.user.client.ui.PasswordTextBox;
import com.google.gwt.user.client.ui.RootPanel;
import com.google.gwt.user.client.ui.ScrollPanel;
import com.google.gwt.user.client.ui.TextBox;
import com.google.gwt.dom.client.Style.Unit;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.http.client.Request;
import com.google.gwt.http.client.RequestBuilder;
import com.google.gwt.http.client.RequestCallback;
import com.google.gwt.http.client.RequestException;
import com.google.gwt.http.client.Response;
import com.google.gwt.http.client.URL;
import com.google.gwt.i18n.client.Dictionary;
import com.google.gwt.json.client.JSONObject;
import com.google.gwt.json.client.JSONParser;
import com.google.gwt.json.client.JSONValue;
import com.smartgwt.client.widgets.grid.ListGrid;
import com.smartgwt.client.widgets.grid.ListGridField;
import com.google.gwt.user.client.ui.Label;


public class TestGUI {

	// GUI Variables
    final static RootPanel rootPanel = RootPanel.get();
    final static LayoutPanel logoPanel = new LayoutPanel(); // Panel 1
    final static LayoutPanel loginPanel = new LayoutPanel(); // Panel 2
    final static LayoutPanel splashPanel = new LayoutPanel(); // Panel 3
    final static LayoutPanel weatherPanel = new LayoutPanel(); //Panel 4
    final static LayoutPanel listPanel = new LayoutPanel(); // Panel 1
    final static LayoutPanel navPanel = new LayoutPanel(); // Panel 2
    final static LayoutPanel inputPanel = new LayoutPanel(); // Panel 3a
    final static AbsolutePanel displayPanel = new AbsolutePanel(); // Panel 3a
    final static ScrollPanel scroll = new ScrollPanel(); // Panel 3
    
    final static int GRID_WIDTH = 20;
    final static int GRID_HEIGHT = 20;
    final static ModuleDragController dragController = new ModuleDragController(displayPanel);
    final static GridConstrainedDropController gridDropController = new GridConstrainedDropController(displayPanel, GRID_WIDTH, GRID_HEIGHT);
    
    
    static TextBox userName = new TextBox();
    static PasswordTextBox password = new PasswordTextBox();
    static Grid grid = new Grid(51,101);
    final static ListGrid table = new ListGrid();
	final static Image nasaEsa = new Image("images/nasaEsa.jpg");
    final static Image wunderLogo = new Image("images/wunderground-logo.jpg");
	
	final static TextBox coord1 = new TextBox();
    final static TextBox coord2 = new TextBox();	
    final static TextBox moduleCode = new TextBox();
	final static ListBox status = new ListBox();
	final static ListBox orientation = new ListBox();
    
    // Labels for GUI
    static Label lblWelcome = new Label("Welcome to the NASA/ESA");
    static Label lblSoftware = new Label("Mars Configuration Software");
    static Label lblLoginToBegin = new Label("Login to begin");
    static Label lblIdentification = new Label("NASA/ESA Identification");
    static Label lblSecurityKey = new Label("Security Key");
    static Label lblModCode = new Label("Module Code Number");
    static Label lblEastWest = new Label("East-West");
    static Label lblNorthSouth = new Label("North-South");
    static Label lblModCoords = new Label("Module Position Coordinates");
    static Label lblModStatus = new Label("Module Status");
    static Label lblModOrient = new Label("Module Orientation");
    static Label lblOptimal = new Label("");
    static Label lblVis = new Label("Visibility:");
    static Label lblTemp = new Label("Temp:");
    
    // Button Variables
    static Button btnLogout = new Button("Logout");
    static Button btnLogin = new Button("Submit");
    static Button btnMinConfigAvail = new Button("Minimal Configuration Available");
    static Button btnConfigOptimal = new Button("Configure Optimal Configuration");
    static Button btnOptimalNext = new Button("Next");
    static Button btnOptimalSelect = new Button("Select Configuration");
    static Button btnLogModules = new Button("Module Input Screen");
    static Button btnModuleDisplay = new Button("Module Display");
    static Button btnGPS = new Button("GPS");
    static Button btnLoad = new Button("Load");
    static Button btnSave = new Button("Save");
    static Button btnSubmitModule = new Button("Submit Module");
    
    // Program Variables
    static ArrayList<Table> tableArray = new ArrayList<Table>();
    static ArrayList<Module> moduleArray = new ArrayList<Module>();
    static Layouts layouts = new Layouts();
    static boolean optimalBuilt = false;
    static HabitatLayout displayedLayout;
    static HabitatLayout selectedLayout = layouts.optimal1;
    static String tempString;
    static String visString;

    static ListGridField modNumField = new ListGridField("Module", 80);
    static ListGridField coordX = new ListGridField("X", 30);
    static ListGridField coordY = new ListGridField("Y", 30);
    static ListGridField statusField = new ListGridField("Status", 60);
    static ListGridField orientField = new ListGridField("Orient", 60);
    
    public static void load() {


		table.setAutoFitFieldWidths(true);
    	// format all panels
    	formatLogoPanel();
    	formatLoginPanel();
    	formatWeatherPanel();
    	splashPanel.setStyleName("loginDisplay");
    	splashPanel.setSize("1000px","600px");
    	formatListPanel();
    	formatNavPanel();
        formatGrid();
        formatModuleInput();
    	scroll.setSize("1000px","600px");
    	scroll.setAlwaysShowScrollBars(false);	

    	dragController.registerDropController(gridDropController);
    	dragController.setBehaviorMultipleSelection(false);
    	
        btnMinConfigAvail.setEnabled(false);
        btnConfigOptimal.setEnabled(false); 

        // Status listbox
		status.addItem("undamaged");
		status.addItem("damaged");
		status.addItem("uncertain");
		// Orientation listbox
		orientation.addItem("upright");
		orientation.addItem("needs 1 turn");
		orientation.addItem("needs 2 turns");		
    
        // Button ClickHandler creations        
        btnLogin.addClickHandler(new ClickHandler() {
        	public void onClick(ClickEvent event) {
        		String userTry = null;
        		String userPass = null;
              
        		userTry = userName.getText();
        		userPass = password.getText();
             
                if ((userTry.equals("midway")) && (userPass.equals("password"))) {
					login();
                 	userName.setText(null);
                 	password.setText(null);
             	} else {
             		Sounds.playIncorrectLogInInfo();
                 	Window.alert("The login information entered was incorrect, please try again.");
                  	userName.setText(null);
                  	password.setText(null);
             	}
        	}
        });              

        btnLogout.addClickHandler(new ClickHandler() {
        	public void onClick(ClickEvent event) {
        		logout();
        	}
        });
        
        btnGPS.addClickHandler(new ClickHandler() {
        	public void onClick(ClickEvent event) {
        		loadGPSdata();
				if (!btnModuleDisplay.isEnabled()) {
					btnModuleDisplay.setEnabled(true);
				}
				optimalBuilt = false;
				refreshDisplayList();
        	}
        });      
        
        btnModuleDisplay.addClickHandler(new ClickHandler() {
            public void onClick(final ClickEvent event) {
            	displayCurrentModules();
            	btnLogModules.setEnabled(true);
            }
        });
        
        btnMinConfigAvail.addClickHandler(new ClickHandler() {
            public void onClick(final ClickEvent event) {
            	displayedLayout = layouts.minLayout;
            	displayPlanLayout(layouts.minLayout);
            }
        });
        
        btnLogModules.addClickHandler(new ClickHandler() {
            public void onClick(final ClickEvent event) {
            	login();
            }
        });
        
        btnSave.addClickHandler(new ClickHandler() {
            public void onClick(final ClickEvent event) {
            	Save.array2save(moduleArray);
            	Window.alert("Module Data Saved");
            }
        });
        
        btnLoad.addClickHandler(new ClickHandler() {
            public void onClick(final ClickEvent event) {            	
            	moduleArray = Save.getArrayFromStorage();
                Save.clearStorage();
            	Window.alert("Module Data Loaded");
				login();
				for (Module mod : moduleArray) {
					if (layouts.addToMinimalLayout(mod)) {
						minimumAvailable();
					}
				}
				if (!btnModuleDisplay.isEnabled()) {
					btnModuleDisplay.setEnabled(true);
				}
            	optimalBuilt = false;
				refreshDisplayList();
            }
        });
        
        btnSubmitModule.addClickHandler(new ClickHandler() {
            public void onClick(final ClickEvent event) {
				if (moduleCode.getText() == null || coord1.getText() == null || coord2.getText() == null) { //do nothing            	
            	} else {
					final int code = Integer.parseInt(moduleCode.getText());
					final String condition = status.getValue(status.getSelectedIndex());
					final int orient = orientation.getSelectedIndex();
					final int x = Integer.parseInt(coord1.getText());
					final int y = Integer.parseInt(coord2.getText());
					final Module mod = new Module(code, condition, orient, x, y);    
           
					if (validModule(mod)) {
						Window.alert("Module entered:\n" + mod.toString());
            		
						if (layouts.addToMinimalLayout(mod)) {
							minimumAvailable();
						}
						moduleArray.add(mod);
						if (!btnModuleDisplay.isEnabled()) {
							btnModuleDisplay.setEnabled(true);
						}
						optimalBuilt = false;
						refreshDisplayList();
					} else {
						Sounds.playModNotEntered();
						Window.alert("Module not entered!");
					}      
				}	
			}
        });
		
		btnOptimalNext.addClickHandler(new ClickHandler() {
            public void onClick(final ClickEvent event) {
            	if (displayedLayout == layouts.optimal1) {
            		lblOptimal.setText("Optimal Layout 2 -- " + layouts.optimal2.getOptimizedPercent() + "%");
            		displayedLayout = layouts.optimal2;
            		displayPlanLayout(layouts.optimal2);
            	} else if (displayedLayout == layouts.optimal2) {
            		lblOptimal.setText("Optimal Layout 3 -- " + layouts.optimal3.getOptimizedPercent() + "%");
            		displayedLayout = layouts.optimal3;
            		displayPlanLayout(layouts.optimal3);
            	} else if (displayedLayout == layouts.optimal3) {
            		lblOptimal.setText("Optimal Layout 4 -- " + layouts.optimal4.getOptimizedPercent() + "%");
            		displayedLayout = layouts.optimal4;
            		displayPlanLayout(layouts.optimal4);
            	} else if (displayedLayout == layouts.optimal4) {
            		lblOptimal.setText("Optimal Layout 1 -- " + layouts.optimal1.getOptimizedPercent() + "%");
            		displayedLayout = layouts.optimal1;
            		displayPlanLayout(layouts.optimal1);
            	}
            }
        });		
		
		btnOptimalSelect.addClickHandler(new ClickHandler() {
            public void onClick(final ClickEvent event) {
            	selectedLayout = displayedLayout;
            	btnOptimalSelect.removeFromParent();
            	btnOptimalNext.removeFromParent();
                navPanel.add(btnConfigOptimal); 
                navPanel.setWidgetLeftWidth(btnConfigOptimal, 29.0, Unit.PX, 214.0, Unit.PX);
                navPanel.setWidgetTopHeight(btnConfigOptimal, 210.0, Unit.PX, 30.0, Unit.PX);   
            }
        });
        
        btnConfigOptimal.addClickHandler(new ClickHandler() {
            public void onClick(final ClickEvent event) {
            	if (!optimalBuilt) {
            		buildOptimalLayouts();
            		optimalBuilt = true;
            	}
            	btnConfigOptimal.removeFromParent();
            	navPanel.add(btnOptimalSelect);
                navPanel.setWidgetLeftWidth(btnOptimalSelect, 29.0, Unit.PX, 170.0, Unit.PX);
                navPanel.setWidgetTopHeight(btnOptimalSelect, 210.0, Unit.PX, 30.0, Unit.PX);  
            	navPanel.add(btnOptimalNext);
                navPanel.setWidgetLeftWidth(btnOptimalNext, 172.0, Unit.PX, 100.0, Unit.PX);
                navPanel.setWidgetTopHeight(btnOptimalNext, 210.0, Unit.PX, 30.0, Unit.PX);  

                if (selectedLayout == layouts.optimal1) {
                	lblOptimal.setText("Optimal Layout 1 -- " + layouts.optimal1.getOptimizedPercent() + "%");
                } else if (selectedLayout == layouts.optimal2) {
                	lblOptimal.setText("Optimal Layout 2 -- " + layouts.optimal2.getOptimizedPercent() + "%");
                } else if (selectedLayout == layouts.optimal3) {
                	lblOptimal.setText("Optimal Layout 3 -- " + layouts.optimal3.getOptimizedPercent() + "%");
                } else if (selectedLayout == layouts.optimal4) {
                	lblOptimal.setText("Optimal Layout 4 -- " + layouts.optimal4.getOptimizedPercent() + "%");
                }
            	displayedLayout = selectedLayout;
        		displayPlanLayout(selectedLayout);            	
            }
        });       

    	logout(); // begins program as if logged out.    
    }

	private static void formatLogoPanel() { 
		logoPanel.clear();
		logoPanel.setSize("272px", "250px");
		logoPanel.getElement().getStyle().setProperty("backgroundColor", "#CDCDCD");
		logoPanel.setStyleName("logPanel");        
		logoPanel.add(nasaEsa);    
        logoPanel.setWidgetLeftWidth(nasaEsa, 13.5, Unit.PX, 245.0, Unit.PX);
        logoPanel.setWidgetTopHeight(nasaEsa, 64.0, Unit.PX, 178.0, Unit.PX);    
		logoPanel.add(lblWelcome);  
		logoPanel.setWidgetLeftWidth(lblWelcome, 50.0, Unit.PX, 214.0, Unit.PX);
		logoPanel.setWidgetTopHeight(lblWelcome, 30.0, Unit.PX, 15.0, Unit.PX);  
		logoPanel.add(lblSoftware);
		logoPanel.setWidgetLeftWidth(lblSoftware, 47.5, Unit.PX, 214.0, Unit.PX);
		logoPanel.setWidgetTopHeight(lblSoftware, 45.0, Unit.PX, 15.0, Unit.PX);
		logoPanel.add(lblLoginToBegin);    
		logoPanel.setWidgetLeftWidth(lblLoginToBegin, 87.5, Unit.PX, 214.0, Unit.PX);
		logoPanel.setWidgetTopHeight(lblLoginToBegin, 260.0, Unit.PX, 20.0, Unit.PX);       
	}
    
	private static void formatLoginPanel() {
		loginPanel.clear();
        loginPanel.setSize("272px", "300px");
		loginPanel.getElement().getStyle().setProperty("backgroundColor", "#CDCDCD");
		loginPanel.setStyleName("navigationPanel");        
		loginPanel.add(userName);     
		loginPanel.setWidgetLeftWidth(userName, 60.0, Unit.PX, 150.0, Unit.PX);
		loginPanel.setWidgetTopHeight(userName, 70.0, Unit.PX, 30.0, Unit.PX);        
		loginPanel.add(lblIdentification);   
		loginPanel.setWidgetLeftWidth(lblIdentification, 60.0, Unit.PX, 214.0, Unit.PX);
		loginPanel.setWidgetTopHeight(lblIdentification, 102.5, Unit.PX, 15.0, Unit.PX);      
		loginPanel.add(password);      
		loginPanel.setWidgetLeftWidth(password, 60.0, Unit.PX, 150.0, Unit.PX);
		loginPanel.setWidgetTopHeight(password, 160.0, Unit.PX, 30.0, Unit.PX);  
		loginPanel.add(lblSecurityKey);   
		loginPanel.setWidgetLeftWidth(lblSecurityKey, 60.0, Unit.PX, 214.0, Unit.PX);
		loginPanel.setWidgetTopHeight(lblSecurityKey, 192.5, Unit.PX, 15.0, Unit.PX);     
		loginPanel.add(btnLogin); 
		loginPanel.setWidgetLeftWidth(btnLogin, 95, Unit.PX, 80, Unit.PX);
		loginPanel.setWidgetTopHeight(btnLogin, 248, Unit.PX, 30.0, Unit.PX);
	}	
	private static void formatWeatherPanel() {
        weatherPanel.clear();
        weatherPanel.setSize("270px", "49px");
        weatherPanel.getElement().getStyle().setProperty("backgroundColor", "#CDCDCD");
        weatherPanel.setStyleName("weatherPanel");  
        weatherPanel.add(lblTemp);
        weatherPanel.setWidgetLeftWidth(lblTemp, 15.0, Unit.PX, 40.0, Unit.PX);
        weatherPanel.setWidgetTopHeight(lblTemp, 3.0, Unit.PX, 30.0, Unit.PX);
        weatherPanel.add(lblVis);
        weatherPanel.setWidgetLeftWidth(lblVis, 15.0, Unit.PX, 60.0, Unit.PX);
        weatherPanel.setWidgetTopHeight(lblVis, 27.0, Unit.PX, 30.0, Unit.PX);
        weatherPanel.add(wunderLogo);    
        weatherPanel.setWidgetLeftWidth(wunderLogo, 220, Unit.PX, 50.0, Unit.PX);
        weatherPanel.setWidgetTopHeight(wunderLogo, 0.0, Unit.PX, 50.0, Unit.PX); 

        Label temp = new Label(tempString);
        weatherPanel.add(temp);
        weatherPanel.setWidgetLeftWidth(temp, 90.0, Unit.PX, 70.0, Unit.PX);
        weatherPanel.setWidgetTopHeight(temp, 3.0, Unit.PX, 30.0, Unit.PX);

        Label vis = new Label(visString);
        weatherPanel.add(vis);
        weatherPanel.setWidgetLeftWidth(vis, 90.0, Unit.PX, 200.0, Unit.PX);
        weatherPanel.setWidgetTopHeight(vis, 27.0, Unit.PX, 30.0, Unit.PX);

        getWeather();
        
}

	private static void formatListPanel() { 
        //create grid/log
        table.setWidth(272);
        table.setHeight(250);
        table.setAlternateRecordStyles(true);
        table.setShowAllRecords(true);
        table.setShowEmptyMessage(true);
        table.setEmptyMessage("<br>Click the <b>Submit Module</b> button to populate this table.");

        table.setFields(new ListGridField[]{modNumField, coordX, coordY, statusField, orientField});       
        
        listPanel.clear();
		listPanel.setSize("272px", "300px");
        listPanel.add(table);    
	}
	
	private static void formatNavPanel() {
		navPanel.clear();
		navPanel.setSize("272px", "300px");
        navPanel.getElement().getStyle().setProperty("backgroundColor", "#CDCDCD");
        navPanel.add(btnMinConfigAvail); 
        navPanel.setWidgetLeftWidth(btnMinConfigAvail, 29.0, Unit.PX, 214.0, Unit.PX);
        navPanel.setWidgetTopHeight(btnMinConfigAvail, 150.0, Unit.PX, 30.0, Unit.PX); 
        navPanel.add(btnModuleDisplay);
        navPanel.setWidgetLeftWidth(btnModuleDisplay, 29.0, Unit.PX, 214.0, Unit.PX);
        navPanel.setWidgetTopHeight(btnModuleDisplay, 90.0, Unit.PX, 30.0, Unit.PX);
        navPanel.add(btnLogModules);    
        navPanel.setWidgetLeftWidth(btnLogModules, 29.0, Unit.PX, 214.0, Unit.PX);
        navPanel.setWidgetTopHeight(btnLogModules, 30.0, Unit.PX, 30.0, Unit.PX);    
        navPanel.add(btnConfigOptimal);  
        navPanel.setWidgetLeftWidth(btnConfigOptimal, 29.0, Unit.PX, 214.0, Unit.PX);
        navPanel.setWidgetTopHeight(btnConfigOptimal, 210.0, Unit.PX, 30.0, Unit.PX);   
        navPanel.add(lblOptimal);
        navPanel.setWidgetLeftWidth(lblOptimal, 55.0, Unit.PX, 214.0, Unit.PX);
        navPanel.setWidgetTopHeight(lblOptimal, 240.0, Unit.PX, 30.0, Unit.PX);
        navPanel.add(btnLogout);
        navPanel.setWidgetLeftWidth(btnLogout, 0.0, Unit.PX, 81.0, Unit.PX);
        navPanel.setWidgetTopHeight(btnLogout, 270.0, Unit.PX, 30.0, Unit.PX);
        navPanel.add(btnGPS);
        navPanel.setWidgetLeftWidth(btnGPS, 220, Unit.PX, 80, Unit.PX);
        navPanel.setWidgetTopHeight(btnGPS, 270, Unit.PX, 30.0, Unit.PX);
        navPanel.add(btnLoad);
        navPanel.setWidgetLeftWidth(btnLoad, 90, Unit.PX, 80, Unit.PX);
        navPanel.setWidgetTopHeight(btnLoad, 270, Unit.PX, 30.0, Unit.PX);
        navPanel.add(btnSave);
        navPanel.setWidgetLeftWidth(btnSave, 140, Unit.PX, 80, Unit.PX);
        navPanel.setWidgetTopHeight(btnSave, 270, Unit.PX, 30.0, Unit.PX);
	}	

    public static void logout() {
    	rootPanel.clear();
    	rootPanel.add(logoPanel, 0, 0);
    	rootPanel.add(loginPanel, 0, 300);
    	rootPanel.add(splashPanel, 270, 0);   
        rootPanel.add(weatherPanel, 0, 250);      
	}

    public static void login() {
        scroll.scrollToTop();
        scroll.scrollToLeft();
        scroll.setAlwaysShowScrollBars(false);
    	rootPanel.clear();
    	rootPanel.add(listPanel, 0, 0);
    	rootPanel.add(navPanel, 0, 300);
    	rootPanel.add(scroll, 270, 0);
        rootPanel.add(weatherPanel, 0, 250);
    	formatModuleInput();
        formatWeatherPanel();
    	btnLogModules.setEnabled(false);
    	btnModuleDisplay.setEnabled(true);
    }
    
    private static void formatModuleInput() {
    	scroll.clear();
    	scroll.add(inputPanel);
    	inputPanel.clear();
    	inputPanel.setSize("1000px", "600px");
		inputPanel.setStyleName("displayPanel");
		//TEXTBOXES MUST BE FORMATTED
        //Coordinate text box East-West
        inputPanel.add(coord1);    
        inputPanel.setWidgetLeftWidth(coord1, 200.0, Unit.PX, 55.0, Unit.PX);
        inputPanel.setWidgetTopHeight(coord1, 360.0, Unit.PX, 80.0, Unit.PX);    
        inputPanel.add(coord2);
        inputPanel.setWidgetLeftWidth(coord2, 280.0, Unit.PX, 55.0, Unit.PX);
        inputPanel.setWidgetTopHeight(coord2, 360.0, Unit.PX, 80.0, Unit.PX);
        inputPanel.add(moduleCode);
        inputPanel.setWidgetLeftWidth(moduleCode, 235.0, Unit.PX, 55.0, Unit.PX);
        inputPanel.setWidgetTopHeight(moduleCode, 100.0, Unit.PX, 80.0, Unit.PX);
        
		inputPanel.add(status);
        inputPanel.setWidgetLeftWidth(status, 500.0, Unit.PX, 200.0, Unit.PX);
        inputPanel.setWidgetTopHeight(status, 100.0, Unit.PX, 30.0, Unit.PX);

		inputPanel.add(orientation);
        inputPanel.setWidgetLeftWidth(orientation, 500.0, Unit.PX, 200.0, Unit.PX);
        inputPanel.setWidgetTopHeight(orientation, 360.0, Unit.PX, 30.0, Unit.PX);
            
        inputPanel.add(lblModCode);      
        inputPanel.setWidgetLeftWidth(lblModCode, 190.0, Unit.PX, 200.0, Unit.PX);
        inputPanel.setWidgetTopHeight(lblModCode, 80.0, Unit.PX, 18.0, Unit.PX);  
        inputPanel.add(lblEastWest);    
        inputPanel.setWidgetLeftWidth(lblEastWest, 194.0, Unit.PX, 75.0, Unit.PX);
        inputPanel.setWidgetTopHeight(lblEastWest, 340.0, Unit.PX, 18.0, Unit.PX);    
        inputPanel.add(lblNorthSouth);
        inputPanel.setWidgetLeftWidth(lblNorthSouth, 270.0, Unit.PX, 85.0, Unit.PX);
        inputPanel.setWidgetTopHeight(lblNorthSouth, 340.0, Unit.PX, 18.0, Unit.PX);
        inputPanel.add(lblModCoords);      
        inputPanel.setWidgetLeftWidth(lblModCoords, 175.0, Unit.PX, 250.0, Unit.PX);
        inputPanel.setWidgetTopHeight(lblModCoords, 320.0, Unit.PX, 18.0, Unit.PX);  
        inputPanel.add(lblModStatus);        
        inputPanel.setWidgetLeftWidth(lblModStatus, 499.5, Unit.PX, 200.0, Unit.PX);
        inputPanel.setWidgetTopHeight(lblModStatus, 80.0, Unit.PX, 18.0, Unit.PX);
        inputPanel.add(lblModOrient);
        inputPanel.setWidgetLeftWidth(lblModOrient, 490.0, Unit.PX, 160.0, Unit.PX);
        inputPanel.setWidgetTopHeight(lblModOrient, 340.0, Unit.PX, 18.0, Unit.PX);
        
        inputPanel.add(btnSubmitModule);    
        inputPanel.setWidgetLeftWidth(btnSubmitModule, 370.0, Unit.PX, 214.0, Unit.PX);
        inputPanel.setWidgetTopHeight(btnSubmitModule, 500.0, Unit.PX, 30.0, Unit.PX);    
    }    
    
    private static void formatGrid() {  
    	//clear all the widgets from the display panel
    	scroll.clear();
    	scroll.add(displayPanel);
    	displayPanel.clear();
    	//Make the panel scrollable
    	int displayPanelWidth = GRID_WIDTH * 100;
    	int displayPanelHeight = GRID_HEIGHT * 50;
    	displayPanel.setSize(displayPanelWidth + "px", displayPanelHeight + "px"); 
    	displayPanel.setStyleName("displayPanel");
    	scroll.setAlwaysShowScrollBars(true);
      
    	/*  // GRID IS NOT NEEDED ANYMORE
    	//Make a grid and set the height, width, padding, and spacing
    	grid.setWidth("1200px");
    	grid.setCellPadding(0);
    	grid.setCellSpacing(0);
    	grid.setHeight("1020x");      
      
    	//If Cell coordinates are (0,n) or (n,0) DO NOT ALLOW THIS!!!!
    	//Create the cells and give each CSS Properties
    	//for (int row = 1; row < 50; row++) {
    	//    for (int col = 1; col < 100; col++) {
    	//    	
    	//    }
    	//}
    	grid.setStylePrimaryName("grid");
    	displayPanel.add(grid);
    	*/
    }    
    
    private static void minimumAvailable() {
    	if (!btnMinConfigAvail.isEnabled()) {
    		btnMinConfigAvail.setEnabled(true);
    	}
    	if (!btnConfigOptimal.isEnabled()) {
    		btnConfigOptimal.setEnabled(true);
    	}
    }
    
    private static void displayCurrentModules() {
    	formatGrid();
    	grid.clear();
        btnLogModules.setEnabled(true);
        for (int x = 40; x <= 50; x++) {
    		for (int y = 40; y <= 50; y++) {
    			displayPanel.add(new Image("images/Sandy2.jpg"), (x - 1) * GRID_WIDTH, (50 - y) * GRID_HEIGHT);
        		//grid.setWidget(50 - y, x, new Image("images/Sandy2.jpg")); 
    		}
    	}
    	for (Module mod : moduleArray) {
    		if (mod.getStatus().equals("undamaged") || mod.getStatus().equals("uncertain")) {
    			//DragModule dMod = new DragModule(mod, "images/" + mod.getType() + ".jpg");
    			//dragController.makeDraggable(dMod);
    			displayPanel.add(new Image("images/" + mod.getType() + ".jpg"), (mod.getX() - 1) * GRID_WIDTH, (50 - mod.getY()) * GRID_HEIGHT);
    			//grid.setWidget(50 - mod.getY(), mod.getX(), new Image("images/" + mod.getType() + ".jpg"));
    		} else if (mod.getStatus().equals("damaged")) {
    			//DragModule dMod = new DragModule(mod, "images/" + mod.getType() + "D.jpg");
    			//dragController.makeDraggable(dMod);
    			displayPanel.add(new Image("images/" + mod.getType() + "D.jpg"), (mod.getX() - 1) * GRID_WIDTH, (50 - mod.getY()) * GRID_HEIGHT);
    			//grid.setWidget(50 - mod.getY(), mod.getX(), new Image("images/" + mod.getType() + "D.jpg"));
    		}
    	}    	
    }  
    
    public static HabitatLayout getCurrentLayout() {
    	return displayedLayout;
    }
    
    public static void refreshPlanDisplay() {
    	displayPlanLayout(displayedLayout);
    }
    
    private static void displayPlanLayout(HabitatLayout layout) { 
    	formatGrid();
        btnModuleDisplay.setEnabled(true);
        btnLogModules.setEnabled(true);    
    	for (int x = 1; x <= 100; x++) {
            for (int y = 1; y <= 50; y++) {
            	//if (!layout.isUsable(x, y) && (layout.getModule(x, y) == null)) {
            	if (!layout.isUsable(x, y)) {
        			displayPanel.add(new Image("images/Sandy2.jpg"), (x - 1) * GRID_WIDTH, (50 - y) * GRID_HEIGHT);
            		//grid.setWidget(50 - y, x, new Image("images/Sandy2.jpg"));            		
            	}
            	if (layout.getModule(x, y) != null) {
            		if (layout.getModule(x, y).getStatus().equals("undamaged") && layout.isUsable(x, y) && layout.isOpen(x, y)) {
            			DragModule dMod = new DragModule(layout.getModule(x, y), "images/" + layout.getModule(x, y).getType() + ".jpg");
            			dragController.makeDraggable(dMod);
            			displayPanel.add(dMod, (x - 1) * GRID_WIDTH, (50 - y) * GRID_HEIGHT);
            		//} else if (layout.getModule(x, y).getStatus().equals("uncertain")) {
            		} else if (layout.isUsable(x, y) && (!layout.isOpen(x, y) || layout.getModule(x, y).getStatus().equals("uncertain"))) {
            			DragModule dMod = new DragModule(layout.getModule(x, y), "images/" + layout.getModule(x, y).getType() + "P.jpg");
            			dragController.makeDraggable(dMod);
            			displayPanel.add(dMod, (x - 1) * GRID_WIDTH, (50 - y) * GRID_HEIGHT);            			
            			//grid.setWidget(50 - y, x, new Image("images/" + layout.getModule(x, y).getType() + "P.jpg"));        			
            		//} else if (layout.getModule(x, y).getStatus().equals("damaged")) {
            		} else if (!layout.isUsable(x, y)) {
            			DragModule dMod = new DragModule(layout.getModule(x, y), "images/" + layout.getModule(x, y).getType() + "D.jpg");
            			//dragController.makeDraggable(dMod);
            			displayPanel.add(dMod, (x - 1) * GRID_WIDTH, (50 - y) * GRID_HEIGHT);
            			//grid.setWidget(50 - y, x, new Image("images/" + layout.getModule(x, y).getType() + "D.jpg"));            			
            		}
            	} else { // (x, y) == null
            		//if (grid.getWidget(50 - y, x) != null) {
            		//	grid.setWidget(50 - y, x, null);
            		//}
            	}
            	
            }
    	}
    }    

	private static void loadGPSdata() {
		Sounds.playGPSLoading();
		Window.alert("GPS data loading");
    	Dictionary d;
        int code = 0;
        String status = "";
        int turns = 0;
        int x = 0;
        int y = 0;
        
        try {
        	for (int i=1;;i++) {
        		d = Dictionary.getDictionary("module"+i); 
        	    code = Integer.parseInt(d.get("code"));
        	    status = d.get("status");
        	    turns = Integer.parseInt(d.get("turns"));
        	    x = Integer.parseInt(d.get("X"));
        	    y = Integer.parseInt(d.get("Y"));
        	    
        	    if (code > 0) {
        	    	Module mod = new Module(code, status, turns, x, y);
        	    	if (validModule(mod)) {
                		if (layouts.addToMinimalLayout(mod)) {
                			minimumAvailable();
                		}
        	    		moduleArray.add(mod);
        	    	}
        	    }
        	}
        }
        catch (Exception e) {};        
    }	
	
	private static void refreshDisplayList() {
        TableData.buildRecords(moduleArray);
        table.setData(TableData.getRecords());
        table.sort();
        //table.redraw();
	}
	
	private static boolean validModule(Module mod) {
    	if (mod == null || mod.getCode() == 0) {
    		return false;
    	} else {
    		boolean valid = true;
    		for (Module arrayMod: moduleArray) {
    			if (arrayMod.getCode() == mod.getCode()) {
    				Sounds.playModCodeEntered();
    				//Window.alert("Module Code already entered, please check again");
    				valid = false;            				
    			} else if (arrayMod.getX() == mod.getX() && arrayMod.getY() == mod.getY()) {
    				Window.alert("Module already entered at X:" + mod.getX() + ", " + mod.getY() + ", please check again");
    				valid = false;
    			}
    		}
    		return valid;
    	}
    } 
	
    private static void buildOptimalLayouts() {
    	layouts.optimal1.addModuleList(moduleArray);
    	layouts.optimal2.addModuleList(moduleArray);
    	layouts.optimal3.addModuleList(moduleArray);
    	layouts.optimal4.addModuleList(moduleArray);
    }
    
    private static void getWeather() {
        
        String proxy = "http://www.d.umn.edu/~gieri002/Weather.php?url=";
        String url = proxy+"http://api.wunderground.com/api/a4e7563412689635/conditions/q/55812.json";       
        url = URL.encode(url);
        // Send request to server and catch any errors.
        RequestBuilder builder = new RequestBuilder(RequestBuilder.GET, url);

        try {
        	Request request = builder.sendRequest(null, new RequestCallback() {                
        		public void onError(Request request, Throwable exception) {
        			Window.alert("onError: Couldn't retrieve JSON");
        		}
                
        		public void onResponseReceived(Request request, Response response) {
        			if (200 == response.getStatusCode()) {
        				String rt = response.getText();
        				update(rt); //METHOD CALL TO DO SOMETHING WITH RESPONSE TEXT
        			} else {
        				Window.alert("Couldn't retrieve JSON (" + response.getStatusCode() + ")");
        			}
        		}
        	});
        } catch (RequestException e) {
        	Window.alert("RequestException: Couldn't retrieve JSON");
        }
    }

private static void update(String rt) {
          String sAll = rt;
          JSONObject jA = 
            (JSONObject)JSONParser.parseLenient(sAll);
          JSONValue jTry = jA.get("current_observation");   
          JSONObject jB =
            (JSONObject)JSONParser.parseLenient(jTry.toString());
          JSONValue temp = jB.get("temp_c");
          JSONValue visibility = jB.get("visibility_km");     
          tempString = "    " + temp.toString() + "\u00b0" + " C";      
          visString = visibility.toString();    
          String result = visString.substring(1, visString.length()-1);
          visString = result + " kilometers";        
}
}